package com.kaluli.project.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.transaction.Transactional;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.kaluli.project.domain.entity.KllMq;
import com.kaluli.project.domain.entity.KllUserDataVo;
import com.kaluli.project.utils.DateUtil;

/**
 * @author niwei
 */
@Service
@Configuration
@Transactional
@PropertySource({ "classpath:mail.properties" })
public class SimpleDatasheetService {
	
	@Autowired
	private Environment env;

    private static final String[] titles = {
            "用户ID", "用户名", "注册时间", "收货人姓名", "地区", "街道","收货人电话","邮编","身份证号"};

    //sample data to fill the sheet.
    private static final String[][] data = {
            {"AngelaBaby", "跑了", "跑了", "跑了", "跑了", "跑了"},
            {"邓超", "跑了", "跑了", "没跑", "跑了", "跑了" },
            {"王祖蓝", "没跑", "没跑", "没跑", "跑了", "341124199003291410" },
            {"王宝强", "跑了", "跑了", "跑了", "跑了", "跑了" },
            {"郑恺", "跑了", "跑了", "跑了", "跑了", "跑了" }
    };
    
    

    public void sendEmailByTime(List<KllUserDataVo> list) throws Exception {

         Workbook wb = new HSSFWorkbook();
         String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        Sheet sheet = wb.createSheet("用户数据报表");

        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(12.75f);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        //获取要导出的数据
        Row row;
        Cell cell;
        int rownum = 1;
        
       
        for(int m=0;m<list.size();m++,rownum++){
        	 row = sheet.createRow(rownum);
        	 KllUserDataVo vo =list.get(m);
        	 cell = row.createCell(0);
             cell.setCellValue(vo.getId());
             cell = row.createCell(1);
             cell.setCellValue(vo.getUser_name());
             cell = row.createCell(2);
             cell.setCellValue(vo.getCt_time());
             cell = row.createCell(3);
             cell.setCellValue(vo.getName());
             cell = row.createCell(4);
             cell.setCellValue(vo.getRegion());
             cell = row.createCell(5);
             cell.setCellValue(vo.getStreet());
             cell = row.createCell(6);
             cell.setCellValue(vo.getMobile());
             cell = row.createCell(7);
             cell.setCellValue(vo.getPostcode());
             cell = row.createCell(8);
             cell.setCellValue(vo.getIdentity_number());
        	 
        }
       
       
       /* for (int i = 0; i < data.length; i++, rownum++) {
            row = sheet.createRow(rownum);
            if(data[i] == null) continue;

            for (int j = 0; j < data[i].length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(data[i][j]);
            }
        }
*/
        System.out.println("Default column width: " + sheet.getRow(0).getLastCellNum());
        System.out.println("Default column width: " + sheet.getRow(0).getPhysicalNumberOfCells());
        
        // Write the output to a file
        String file = "用户数据报表_"+date+".xls";
        FileOutputStream out = new FileOutputStream(file);
        wb.write(out);
        out.close();
        
        sendMail(file);
        
        // 删除临时文件
		File dayReportFile = new File(file);
		dayReportFile.delete();
    }
    
    /**
	 * 发送日报
	 * 
	 * @param propMap
	 * @param dayReportName
	 * @throws MessagingException
	 * @throws IOException
	 */
	private  void sendMail(String dayReportName) throws MessagingException, IOException {
		 Properties props = new Properties();  
	        // 开启debug调试  
	        props.setProperty("mail.debug", "false");  
	        // 发送服务器需要身份验证  
	        props.setProperty("mail.smtp.auth", "true");  
	        // 设置邮件服务器主机名  
	        props.setProperty("mail.host", env.getProperty("nsapi.mail.smtp"));   
	        // 发送邮件协议名称  
	        props.setProperty("mail.transport.protocol", "smtp");  
	          
	        // 设置环境信息  
	        Session session = Session.getInstance(props);  
	          
	        // 创建邮件对象  
	        Message msg = new MimeMessage(session);  
	        String time =DateUtil.date2Str(new Date(), "yyyy-MM-dd");
	        msg.setSubject(env.getProperty("nsapi.mail.datatitle")+"&"+time);  
	        
	    	// 设置发送人
			MimeMultipart partList = new MimeMultipart();
			// 写附件
			MimeBodyPart part2 = new MimeBodyPart();
			part2.attachFile(new File(dayReportName));
			part2.setFileName(MimeUtility.encodeText(dayReportName));
			// 把部件添加到集合中
//			partList.addBodyPart(part1);
			partList.addBodyPart(part2);
			msg.setContent(partList);
			
			 //设置自定义发件人昵称    
	        String nick="";    
	        try {    
	            nick=javax.mail.internet.MimeUtility.encodeText(env.getProperty("nsapi.mail.kaluli"));    
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();    
	        }
			
	        // 设置发件人 
//	        msg.setFrom(new InternetAddress(env.getProperty("nsapi.mail.sender")));  
	        msg.setFrom(new InternetAddress(nick+" <"+env.getProperty("nsapi.mail.sender")+">")); 
	          
	        Transport transport = session.getTransport();  
	        String emails=env.getProperty("nsapi.mail.userdata");
	        String[] s =emails.split(",");
	        InternetAddress[] address = new InternetAddress[s.length];
	        for(int i=0;i<s.length;i++){
	        	address[i]=new InternetAddress(s[i]);
	        }
	        // 连接邮件服务器  (用户名密码)
	        transport.connect(env.getProperty("nsapi.mail.username"), env.getProperty("nsapi.mail.password"));
	        // 发送邮件  
	        transport.sendMessage(msg, address);
	        // 关闭连接  
	        transport.close();  
	
	}
}